//----------------------------------------------------------------------------
// View 'Herhaalrecept'
//----------------------------------------------------------------------------
Ti.include('lib/include.js');
Ti.include('lib/constants.js');
Ti.include('lib/strings.js');
Ti.include('lib/stringbuilder.js');
Ti.include('data/db.js');
Ti.include('hhrecept_datepicker_ios.js');
Ti.include('hhrecept_apotheekpicker_ios.js');
Ti.include('hhrecept_history_ios.js');


//datum herhaalrecept, key
var selectedHHreceptDT;

//genomen afbeelding van medicijn, als bijlage in genereerde mail met aanvraag
var imgMedicijn;

//indicatie of afbeelding moet worden opgenomen in aanvraag
var isImage = false;


var winHHRecept = Titanium.UI.currentWindow;

winHHRecept.addEventListener('focus', function(e) {
   log("Window 'Herhaalrecept' actief");
});

// button 'Historie'
var btnHistorie = Titanium.UI.createButton({
   title : T_HHRECEPT_BTN_HISTORY
});
btnHistorie.addEventListener('click', showViewHistorie);
winHHRecept.leftNavButton = btnHistorie;

// button 'Bellen' -> alleen voor iphone
if (isIphone()) {
   var btnHHReceptBellen = Titanium.UI.createButton({
      title : T_HHRECEPT_BTN_CALL
   });
   btnHHReceptBellen.addEventListener('click', function(e) {
      hhreceptBellenDialog.show();
   });
   var hhreceptBellenDialog = Titanium.UI.createAlertDialog({
      title : 'Voor herhaalrecepten kunt u ook direct de praktijk bellen. Kies vervolgens optie 2.\nWilt u dit nu doen?',
      buttonNames : ['OK', 'Annuleren'],
      cancel : 1
   });
   hhreceptBellenDialog.addEventListener('click', function(event) {
      if (event.index == 0) {
         Titanium.Platform.openURL('tel:0433614444');
      }
   });
   winHHRecept.rightNavButton = btnHHReceptBellen;
}

function showViewHistorie() {
   winHHRecept.remove(viewHHRecepten);
   winHHRecept.add(viewHistorie);
   winHHRecept.leftNavButton = btnTerug;
   winHHRecept.rightNavButton = btnHistorieWissen;
   //
   populateTableHistorie();
}


//----------------------------------------------------------------------------
// View 'Herhaalrecepten'
//----------------------------------------------------------------------------
var viewHHRecepten = Ti.UI.createScrollView({
   width: '100%',
   contentWidth : 'auto',
   contentHeight : 'auto',
   showVerticalScrollIndicator : true,
   showHorizontalScrollIndicator : true
});

viewHHRecepten.add(Titanium.UI.createLabel({
   textAlign : Ti.UI.TEXTALIGNMENTLEFT,
   font : {
      fontSize : 12,
      fontWeight : 'bold',
      fontFamily : customFont
   },
   color : middenblauw,
   top : '15',
   left : '20',
   text : T_HHRECEPT_FORM_CONTACT
}));

var tfNaam = Ti.UI.createTextField({
   top : '35',
   left : '20',
   width : '90%',
   height : '30',
   paddingLeft : '3',
   backgroundColor: wit,
   font : {
      fontSize : 16,
      fontWeight : 'normal'
   },
   hintText : T_HHRECEPT_FORM_LASTNAME,
   color : middenblauw,
   borderRadius : '2',
   borderColor : middenblauw,
   borderStyle : Titanium.UI.INPUTBORDERSTYLELINE
});

var tfInitialen = Ti.UI.createTextField({
   top : '70',
   left : '20',
   width : '80',
   height : '30',
   paddingLeft : '3',
   backgroundColor: wit,
   font : {
      fontSize : 16,
      fontWeight : 'normal'
   },
   hintText : T_HHRECEPT_FORM_INITIALS,
   color : middenblauw,
   borderRadius : '2',
   borderColor : middenblauw,
   borderStyle : Titanium.UI.INPUTBORDERSTYLELINE
});

var btnSelectDate = Ti.UI.createButton({
   width : '24',
   height : '24',
   backgroundImage : 'images/icons/search32.png'
});
btnSelectDate.addEventListener('click', function(e) {
   winHHRecept.add(viewDatePicker);
});

var tfGebDatum = Ti.UI.createTextField({
   top : '70',
   left : '105',
   width : '130',
   height : '30',
   paddingLeft : '3',
   backgroundColor: wit,
   font : {
      fontSize : 16,
      fontWeight : 'normal'
   },
   hintText : T_HHRECEPT_FORM_BDATE,
   color : middenblauw,
   borderRadius : '2',
   borderColor : middenblauw,
   borderStyle : Titanium.UI.INPUTBORDERSTYLELINE,
   rightButton : btnSelectDate,
   rightButtonMode : Titanium.UI.INPUTBUTTONMODEALWAYS
});

var tfStraat = Ti.UI.createTextField({
   top : '105',
   left : '20',
   width : '90%',
   height : '30',
   paddingLeft : '3',
   backgroundColor: wit,
   font : {
      fontSize : 16,
      fontWeight : 'normal'
   },
   hintText : T_HHRECEPT_FORM_STREET,
   color : middenblauw,
   borderRadius : '2',
   borderColor : middenblauw,
   borderStyle : Titanium.UI.INPUTBORDERSTYLELINE
});

var tfPostcode = Ti.UI.createTextField({
   top : '140',
   left : '20',
   width : '80',
   height : '30',
   paddingLeft : '3',
   backgroundColor: wit,
   font : {
      fontSize : 16,
      fontWeight : 'normal'
   },
   hintText : T_HHRECEPT_FORM_PCODE,
   color : middenblauw,
   borderRadius : '2',
   borderColor : middenblauw,
   borderStyle : Titanium.UI.INPUTBORDERSTYLELINE
});

var tfPlaats = Ti.UI.createTextField({
   top : '140',
   left : '105',
   width : '60%',
   height : '30',
   paddingLeft : '3',
   backgroundColor: wit,
   font : {
      fontSize : 16,
      fontWeight : 'normal'
   },
   hintText : T_HHRECEPT_FORM_PLACE,
   color : middenblauw,
   borderRadius : '2',
   borderColor : middenblauw,
   borderStyle : Titanium.UI.INPUTBORDERSTYLELINE
});

var tfTelefoon = Ti.UI.createTextField({
   top : '175',
   left : '20',
   width : '140',
   height : '30',
   paddingLeft : '3',
   backgroundColor: wit,
   keyboardType: Ti.UI.KEYBOARD_NUMBER_PAD,
   returnKeyType: Ti.UI.RETURNKEY_DONE,
   font : {
      fontSize : 16,
      fontWeight : 'normal'
   },
   hintText : T_HHRECEPT_FORM_PHONE,
   color : middenblauw,
   borderRadius : '2',
   borderColor : middenblauw,
   borderStyle : Titanium.UI.INPUTBORDERSTYLELINE
});

var toolbarDone = Ti.UI.createButton({systemButton: Titanium.UI.iPhone.SystemButton.DONE});
var flexSpace = Titanium.UI.createButton({systemButton : Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE});
toolbarDone.addEventListener('click', function(){tfTelefoon.blur();});
var toolbar = Ti.UI.iOS.createToolbar({
   items: [flexSpace, toolbarDone],
   tintColor: wit,
   barColor: donkergroen
});
tfTelefoon.keyboardToolbar = toolbar;


//----- Herhaalrecept blok
viewHHRecepten.add(Titanium.UI.createLabel({
   textAlign : Ti.UI.TEXTALIGNMENTLEFT,
   font : {
      fontSize : 12,
      fontWeight : 'bold',
      fontFamily : customFont
   },
   color : middenblauw,
   top : '220',
   left : '20',
   text : T_HHRECEPT_FORM_HHRECEPT
}));

var btnMedicijnCapture = Ti.UI.createButton({
   width : '24',
   height : '24',
   backgroundImage : 'images/icons/camera.png'
});
btnMedicijnCapture.addEventListener('click', function(e) {
   medicijnCaptureDialog.show();
});

var medicijnCaptureDialog = Titanium.UI.createOptionDialog({
   title : T_HHRECEPT_DLG_CAPTURE_TITLE,
   options : [T_CAMERA, T_GALLERY, T_CANCEL],
   cancel : 2
});
medicijnCaptureDialog.addEventListener('click', function(e) {
   //Camera
   if (e.index == 0) {
      captureImageFromCamera();
   }
   //Filmrol
   else if (e.index == 1) {
      captureImageFromGallery();
   }
   //Annuleren
   else {
      log("Annuleren gekozen");
   }
});

var tfMedicijn = Ti.UI.createTextField({
   top : '240',
   left : '20',
   width : '90%',
   height : '30',
   paddingLeft : '3',
   backgroundColor: wit,
   font : {
      fontSize : 16,
      fontWeight : 'normal'
   },
   hintText : T_HHRECEPT_FORM_MEDICINE,
   color : middenblauw,
   borderRadius : '2',
   borderColor : middenblauw,
   borderStyle : Titanium.UI.INPUTBORDERSTYLELINE,
   rightButton : btnMedicijnCapture,
   rightButtonMode : Titanium.UI.INPUTBUTTONMODEALWAYS
});

var tfDosering = Ti.UI.createTextField({
   top : '275',
   left : '20',
   width : '100',
   height : '30',
   paddingLeft : '3',
   backgroundColor: wit,
   font : {
      fontSize : 16,
      fontWeight : 'normal'
   },
   hintText : T_HHRECEPT_FORM_DOSE,
   color : middenblauw,
   borderRadius : '2',
   borderColor : middenblauw,
   borderStyle : Titanium.UI.INPUTBORDERSTYLELINE
});

var tfAantal = Ti.UI.createTextField({
   top : '275',
   left : '125',
   width : '120',
   height : '30',
   paddingLeft : '3',
   backgroundColor: wit,
   font : {
      fontSize : 16,
      fontWeight : 'normal'
   },
   hintText : T_HHRECEPT_FORM_AMOUNT,
   color : middenblauw,
   borderRadius : '2',
   borderColor : middenblauw,
   borderStyle : Titanium.UI.INPUTBORDERSTYLELINE
});

var tfGebruik = Ti.UI.createTextField({
   top : '310',
   left : '20',
   width : '90%',
   height : '30',
   paddingLeft : '3',
   backgroundColor: wit,
   font : {
      fontSize : 16,
      fontWeight : 'normal'
   },
   hintText : T_HHRECEPT_FORM_USAGE,
   color : middenblauw,
   borderRadius : '2',
   borderColor : middenblauw,
   borderStyle : Titanium.UI.INPUTBORDERSTYLELINE
});

var btnSelectApotheek = Ti.UI.createButton({
   width : '24',
   height : '24',
   backgroundImage : 'images/icons/search32.png'
});
btnSelectApotheek.addEventListener('click', function(e) {
   winHHRecept.add(viewApotheek);
});

var tfApotheek = Ti.UI.createTextField({
   top : '345',
   left : '20',
   width : '90%',
   height : '30',
   paddingLeft : '3',
   backgroundColor: wit,
   font : {
      fontSize : 16,
      fontWeight : 'normal'
   },
   hintText : T_HHRECEPT_FORM_PHARMACY,
   color : middenblauw,
   borderRadius : '2',
   borderColor : middenblauw,
   borderStyle : Titanium.UI.INPUT_BORDERSTYLE_NONE,
   rightButton : btnSelectApotheek,
   rightButtonMode : Titanium.UI.INPUTBUTTONMODEALWAYS
});

var btnReset = Ti.UI.createButton({
   top : '390',
   left : '20',
   width : '100',
   height : '30',
   font : {
      fontSize : 14,
      fontWeight : 'bold',
      fontFamily : customFont
   },
   color : wit,
   title : T_HHRECEPT_BTN_RESET,
   backgroundColor : hh_lichtblauw,
   backgroundImage : 'images/backgrounds/bg-lichtblauw.png',
   borderRadius : '3',
   borderColor : hh_lichtblauw
});
btnReset.addEventListener('click', function(e) {
   clearTextfieldsDialog.show();
});

var btnAanvragen = Ti.UI.createButton({
   top : '390',
   right : '20',
   width : '100',
   height : '30',
   font : {
      fontSize : 14,
      fontWeight : 'bold',
      fontFamily : customFont
   },
   color : wit,
   title : T_HHRECEPT_BTN_SEND,
   backgroundColor : hh_lichtblauw,
   backgroundImage : 'images/backgrounds/bg-lichtblauw.png',
   borderRadius : '3',
   borderColor : hh_lichtblauw
});
btnAanvragen.addEventListener('click', function(e) {
   if (isValidHHRecept()) {
      sendDialog.show();
   }
});


//----- Dialogs
var clearTextfieldsDialog = Titanium.UI.createAlertDialog({
   title : T_HHRECEPT_DLG_CLEARALL_TITLE,
   message : T_HHRECEPT_DLG_CLEARALL_MESSAGE,
   buttonNames : [T_OK, T_CANCEL],
   cancel : 1
});
clearTextfieldsDialog.addEventListener('click', function(event) {
   if (event.index == 0) {
      clearTextFields();
      Ti.Analytics.featureEvent(APP_EVENTS.EVENT_HHRECEPT_FORM_CLEARED);
   }
});

var sendDialog = Titanium.UI.createAlertDialog({
   title : T_HHRECEPT_DLG_SEND_TITLE,
   message : T_HHRECEPT_DLG_SEND_MESSAGE,
   buttonNames : [T_OK, T_CANCEL],
   cancel : 1
});
sendDialog.addEventListener('click', function(event) {
   if (event.index == 0) {
      sendHHRecept();
   }
});


//----- UI componenten toevoegen
viewHHRecepten.add(tfNaam, tfInitialen, tfGebDatum, tfStraat, tfPostcode, tfPlaats, tfTelefoon);
viewHHRecepten.add(tfMedicijn, tfDosering, tfAantal, tfGebruik, tfApotheek);
viewHHRecepten.add(btnReset, btnAanvragen);
winHHRecept.add(viewHHRecepten);



//----- Functions
function captureImageFromCamera() {
   Titanium.Media.showCamera({
      error : function(error) {
         var errorDialog = Titanium.UI.createAlertDialog({
            title : T_HHRECEPT_DLG_CAPTUREERROR_TITLE
         });
         if (error.code == Titanium.Media.NO_CAMERA) {
            errorDialog.setMessage(T_HHRECEPT_DLG_CAPTUREERROR_MESSAGE);
         }
         else {
            log("Fout: " + error.code);
            errorDialog.setMessage(T_HHRECEPT_DLG_CAPTUREERROR_ERROR + error.code);
         }
         errorDialog.show();
      },
      cancel : function() {
         log("Camera annuleren");
      },
      success : function(event) {
         log("Foto is genomen en wordt verwerkt");
         captureImageFromEvent(event);
      },
      allowImageEditing : true,
      saveToPhotoGallery : true
   });
}

function captureImageFromGallery() {
   Titanium.Media.openPhotoGallery({
      success : function(event) {
         log("Afbeelding geselecteerd uit filmrol");
         captureImageFromEvent(event);
      },
      cancel : function() {
         log("Filmrol annuleren");
      }
   });
}

function captureImageFromEvent(event) {
   var image = event.media;
   if (event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO) {
      var fileName = "snapshot-" + getReversedDate() + ".png";
      var imageFile = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, fileName);
      imageFile.write(event.media);
      log(event.media);
      imgMedicijn = imageFile;
      tfMedicijn.value = "[Afbeelding]";
      isImage = true;
   }
}

function sendHHRecept() {
   var mailContent = 'Betreft: aanvraag herhaalrecept, verzonden via Heerderhof app.\n\n' + 
    '----- Patient gegevens -----\n' +
    'Achternaam: ' + tfNaam.value + "\n" + 
    'Initialen: ' + tfInitialen.value + "\n" +
    'Geboorte datum: ' + tfGebDatum.value + "\n" + 
    'Adres: ' + tfStraat.value + "\n" + 
    'Postcode: ' + tfPostcode.value + "\n" + 
    'Woonplaats: ' + tfPlaats.value + "\n" + 
    'Telefoon: ' + tfTelefoon.value + "\n" + '\n' + 
    '----- Herhaalrecept -----\n' + 
    'Medicijn: ' + tfMedicijn.value + "\n" + 
    'Dosering: ' + tfDosering.value + "\n" + 
    'Aantal: ' + tfAantal.value + "\n" + 
    'Gebruik: ' + tfGebruik.value + "\n" + '\n' + 
    'Gewenste apotheek: ' + tfApotheek.value + "\n" + '\n' + 
    'Neem contact op met patient indien niet alle gegevens zijn ingevuld of er onduidelijkheden zijn.\n';
   
   if (isImage) {
      mailContent = mailContent + T_HHRECEPT_DLG_MAIL_CONTENT2;
   }

   //Genereer email bericht
   var emailDialog = Ti.UI.createEmailDialog();
   emailDialog.subject = T_HHRECEPT_DLG_MAIL_SUBJECT + tfInitialen.value + " " + tfNaam.value;
   emailDialog.toRecipients = [T_HHRECEPT_DLG_MAIL_RECEPIENT];
   emailDialog.messageBody = mailContent;
   emailDialog.html = false;
   if (isImage) {
      log("Afbeelding toevoegen als bijlage");
      emailDialog.addAttachment(imgMedicijn);
   }
   //Open email in mail app
   emailDialog.open();
   //Voeg event listener toe
   emailDialog.addEventListener('complete', function(event) {
      if (event.result == emailDialog.SENT) {
         log("Bericht verzonden");
         storeHHRecept();
         alert('Herhaalrecept aanvraag verzonden');
         clearTextFields();
         Ti.Analytics.featureEvent(APP_EVENTS.EVENT_HHRECEPT_FORM_SENT);
      }
      else if (event.result == emailDialog.CANCELLED) {
         log("Bericht versturen geannuleerd");
      }
      else {
         log("Onbekende fout opgetreden: " + event.toString);
      }
   });
}

function isValidHHRecept() {
   //Controleer of verplichte velden zijn ingevuld
   if (tfNaam.value == "") {
      Titanium.UI.createAlertDialog({
         title : T_HHRECEPT_DLG_CHECKS_TITLE,
         message : T_HHRECEPT_DLG_CHECKS_NAME
      }).show();
      return false;
   }
   if (tfGebDatum.value == "") {
      Titanium.UI.createAlertDialog({
         title : T_HHRECEPT_DLG_CHECKS_TITLE,
         message : T_HHRECEPT_DLG_CHECKS_BDATE
      }).show();
      return false;
   }
   if (tfStraat.value == "" || tfPostcode.value == "" || tfPlaats.value == "") {
      Titanium.UI.createAlertDialog({
         title : T_HHRECEPT_DLG_CHECKS_TITLE,
         message : T_HHRECEPT_DLG_CHECKS_ADDRESS
      }).show();
      return false;
   }
   /*
    if (tfTelefoon.value == "") {
    Titanium.UI.createAlertDialog({title: T_HHRECEPT_DLG_CHECKS_TITLE, message:'Voer uw telefoonnummer in a.u.b.'}).show();
    return false;
    }
    */
   if (tfMedicijn.value == "") {
      Titanium.UI.createAlertDialog({
         title : T_HHRECEPT_DLG_CHECKS_TITLE,
         message : T_HHRECEPT_DLG_CHECKS_MEDICINE
      }).show();
      return false;
   }
   if (tfDosering.value == "") {
      Titanium.UI.createAlertDialog({
         title : T_HHRECEPT_DLG_CHECKS_TITLE,
         message : T_HHRECEPT_DLG_CHECKS_DOSE
      }).show();
      return false;
   }
   if (tfAantal.value == "") {
      Titanium.UI.createAlertDialog({
         title : T_HHRECEPT_DLG_CHECKS_TITLE,
         message : T_HHRECEPT_DLG_CHECKS_AMOUNT
      }).show();
      return false;
   }
   if (tfApotheek.value == "") {
      Titanium.UI.createAlertDialog({
         title : T_HHRECEPT_DLG_CHECKS_TITLE,
         message : T_HHRECEPT_DLG_CHECKS_PHARMACY
      }).show();
      return false;
   }

   //All OK
   return true;
}

function storeHHRecept() {
   hhreceptendb = Ti.Database.open('hhrecepten');
   if (isImage) {
      log('Herhaalrecept met afbeelding wordt opgeslagen in database');
      hhreceptendb.execute('INSERT INTO hhrecepten (date_time, name, initials, bdate, street, postcode, place, phone, medicine, dose, number, usage, pharmacy, image) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', getDate(), tfNaam.value, tfInitialen.value, tfGebDatum.value, tfStraat.value, tfPostcode.value, tfPlaats.value, tfTelefoon.value, tfMedicijn.value, tfDosering.value, tfAantal.value, tfGebruik.value, tfApotheek.value, imgMedicijn.nativePath);
   }
   else {
      log('Herhaalrecept zonder afbeelding wordt opgeslagen in database');
      hhreceptendb.execute('INSERT INTO hhrecepten (date_time, name, initials, bdate, street, postcode, place, phone, medicine, dose, number, usage, pharmacy) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', getDate(), tfNaam.value, tfInitialen.value, tfGebDatum.value, tfStraat.value, tfPostcode.value, tfPlaats.value, tfTelefoon.value, tfMedicijn.value, tfDosering.value, tfAantal.value, tfGebruik.value, tfApotheek.value);
   }
   hhreceptendb.close();
}

function clearTextFields() {
   log("Invoervelden wissen");
   tfNaam.value = '';
   tfInitialen.value = '';
   tfGebDatum.value = '';
   tfStraat.value = '';
   tfPostcode.value = '';
   tfPlaats.value = '';
   tfTelefoon.value = '';
   tfMedicijn.value = '';
   tfDosering.value = '';
   tfAantal.value = '';
   tfGebruik.value = '';
   tfApotheek.value = '';
   //
   if (isImage) {
      log("Gekozen afbeelding verwijderen");
      isImage = false;
      imgMedicijn = null;
   }
}

